﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TDT.Land.Entity;
using TDT.Land.Utilities;
using TDT.Land.BusinessLogic;
using TDT.Land.Models;
using System.Web.Routing;
using System.IO;
using System.Text.RegularExpressions;

namespace TDT.Land.Web.Controllers
{
    public class ProLandController : BaseController
    {
        //
        // GET: /Admin/
        //[Extent.CustomAuthorize(Roles = LandType.E_ADMIN + "|"+ LandType.E_ADMIN_ROOT)]
        [CustomAuthorize(Roles = "2")]
        public ActionResult Index()
        {
            return View();
        }
        [CustomAuthorize(Roles = "2")]
        public ActionResult AD_openEdit(string id)
        {
            Guid ID = id != string.Empty ? Guid.Parse(id) : Guid.Empty;
            Pro_Land LandInfo = AdminRepo.Instance.GetProLandById(ID);
            //tại đây lấy thêm các bộ enum kèm theo để truyền vào dropdownlist

            List<Cat_LandModel> lstHomeType = AdminRepo.Instance.GetCatLands(CategoryType.E_LAND_HOME_TYPE.ToString());
            List<Cat_LandModel> lstBDSType = AdminRepo.Instance.GetCatLands(CategoryType.E_LAND_BDS_TYPE.ToString());
            List<Cat_ProvinceModel> lstProvince = AdminRepo.Instance.GetProvinces();
            List<Cat_WardModel> lstWard = AdminRepo.Instance.GetWards();
            List<Cat_DistrictModel> lstDistrict = AdminRepo.Instance.GetDistricts();

            

            string HomeTypeID = string.Empty;
            string BDSTypeID = string.Empty;
            string ProvinceID = string.Empty;
            string WardID = string.Empty;
            string DistricID = string.Empty;
            if (LandInfo != null)
            {
                if (LandInfo.LandTypeId != null)
                {
                    HomeTypeID = LandInfo.LandTypeId.ToString();
                }
                if (LandInfo.LandTypeBDSId != null)
                {
                    BDSTypeID = LandInfo.LandTypeBDSId.ToString();
                }

                if (LandInfo.ProvinceId != null)
                {
                    ProvinceID = LandInfo.ProvinceId.ToString();
                }
                if (LandInfo.DistrictId != null)
                {
                    DistricID = LandInfo.DistrictId.ToString();
                }
                if (LandInfo.WardId != null)
                {
                    WardID = LandInfo.WardId.ToString();
                }
            }
            ViewBag.select_HomeType = Commons.ConvertToSelectListItems(lstHomeType, Cat_LandModel.FieldName.Id, Cat_LandModel.FieldName.LandCategoryName, HomeTypeID);
            ViewBag.select_BDSType = Commons.ConvertToSelectListItems(lstBDSType, Cat_LandModel.FieldName.Id, Cat_LandModel.FieldName.LandCategoryName, BDSTypeID);
            ViewBag.select_Ward = Commons.ConvertToSelectListItems(lstWard, Cat_WardModel.FieldName.Id, Cat_WardModel.FieldName.WardName, WardID);
            ViewBag.select_District = Commons.ConvertToSelectListItems(lstDistrict, Cat_DistrictModel.FieldName.Id, Cat_DistrictModel.FieldName.DistrictName, DistricID);
            ViewBag.select_Province = Commons.ConvertToSelectListItems(lstProvince, Cat_ProvinceModel.FieldName.Id, Cat_ProvinceModel.FieldName.ProvinceName, ProvinceID);
            ViewBag.select_Currency = Commons.ConvertToSelectListItems(typeof(CurrencyType),true);

               
            ViewBag.select_LandStatus = Commons.ConvertToSelectListItems(typeof(LandStatus));

            return View("Land_Edit", LandInfo);

            //return PartialView("Land_Edit", LandInfo);
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult AD_LandList()
        {
            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLands();
            ViewBag.lstLand = lstLand;

            int itemCount = AdminRepo.Instance.GetCountItemLand();
            int totalPage = itemCount / 20;
            if ((itemCount % 2) > 0)
                totalPage++;

            ViewBag.CountItem = totalPage.ToString();

            return View();
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult AD_GetLand(int NumPage, int NumRow)
        {
            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLands(NumPage, NumRow);
            ViewBag.lstLand = lstLand;
            return PartialView("UC_AD_Land_List");
        }


        [HttpPost]
        [ValidateInput(false)]        
        public ActionResult LandAction(Pro_Land model, HttpPostedFileBase NAMEbtnUpload, FormCollection forms)
        {

            //string Error = Commons.ValidateModelState(ModelState);
            //if(Error!= string.Empty)
            //    return Content(Error);



            bool result = false;
            if (model.ID == null || model.ID == Guid.Empty) // Tạo mới
            {
                var imgurl = Upload();
                model.LandImage = imgurl;
                model.DateCreate = DateTime.Now;
                model.ID = Guid.NewGuid();
                model.UserCreate = UserNameFull;
                result = AdminRepo.Instance.CreateProLand(model, UserName);
            }
            else //Chinh sua
            {
                var imgurl = Upload();
                if (imgurl != "")
                {
                    model.LandImage = imgurl;
                    model.UserUpdate = UserNameFull;
                }
                result = AdminRepo.Instance.UpdateProLand(model, UserName);
            }
            return Content(result.ToString());
        }

        [CustomAuthorize(Roles = "2")]
        public ActionResult AD_LandDelete(string strLandId)
        {
            bool result = false;
            var arrLanId = strLandId.Split(';');
            foreach (var item in arrLanId)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    Guid _proLandId = new Guid(item);

                    result = AdminRepo.Instance.DeleteProLand(_proLandId, UserName);
                }
            }

           // result = AdminRepo.Instance.DeleteProLand(model);

            string _statusDelete = "00";
            if (result)
                _statusDelete = "01";

            return Content(_statusDelete);
        }


        public string Upload()
        {
            var status = "";
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
                    file.SaveAs(path);
                    status = fileName;
                }
            }

            return status;
        }


        #region user Site


        public ActionResult GetLand()
        {
            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLands();
            foreach (Pro_LandModel itemLand in lstLand)
            {
                if (!string.IsNullOrEmpty(itemLand.Description))
                {
                    itemLand.Description = Regex.Replace(itemLand.Description, @"<img\s[^>]*>(?:\s*?/>)?", "", RegexOptions.IgnoreCase);
                    itemLand.Description = Regex.Replace(itemLand.Description, @"<(.|\n)*?>", string.Empty);
                    int descLength = itemLand.Description.Length;
                    if (descLength > 350)
                        itemLand.Description = itemLand.Description.Substring(0, 350) + "...";
                }
            }

            int itemCount = AdminRepo.Instance.GetCountItemLand();
            int totalPage = itemCount / 20;
            if ((itemCount % 2) > 0)
                totalPage++;

            ViewBag.CountItem = totalPage.ToString();
            ViewBag.lstLand = lstLand;
            return View();
        }

        public ActionResult GetLandIsShowTop()
        {
            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLandShowTop();
            ViewBag.lstLand = lstLand;
            return PartialView("US_UC_SlideLeft");
        }


        public ActionResult ViewLand(string id)
        {
            Guid ID = id != string.Empty ? Guid.Parse(id) : Guid.Empty;
            Pro_LandModel proLand = AdminRepo.Instance.GetProLandViewById(ID);
            
            ViewBag.PrLand = proLand;
            return View();
        }

        //NguyenDuy open detail user
        public ActionResult ViewLandByUrl(string url)
        {
            Pro_LandModel proLand = AdminRepo.Instance.GetProLandViewByUrl(url);
            ViewBag.PrLand = proLand;

            var ext = AdminRepo.Instance.GetProBuildingByCode("lien-he", UserName);
            ViewBag.Bcontent = ext;

            return View("ViewLand");
        }

        public ActionResult SearchLand()
        {
            Guid Province = Guid.Empty;
            Guid District = Guid.Empty;
            Guid Ward = Guid.Empty;
            Guid HomeType = Guid.Empty;
            Guid BDSType = Guid.Empty;
            Guid.TryParse(Request.Params["select_Province"].ToString(), out Province);
            Guid.TryParse(Request.Params["DistrictId"].ToString(), out District);
            Guid.TryParse(Request.Params["WardId"].ToString(), out Ward);
            Guid.TryParse(Request.Params["select_HomeType"].ToString(), out HomeType);
            Guid.TryParse(Request.Params["select_BDSType"].ToString(), out BDSType);

            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLandsBySearch(1, 1000, Province, District, Ward, HomeType, BDSType);
            return PartialView("UC_Us_Land_List", lstLand);
        }

        /// <summary>
        /// View user site
        /// </summary>
        /// <param name="NumPage"></param>
        /// <param name="NumRow"></param>
        /// <returns></returns>
        public ActionResult LandList(int NumPage, int NumRow)
        {
            List<Pro_LandModel> lstLand = AdminRepo.Instance.GetProLands(NumPage, NumRow);
            foreach (Pro_LandModel itemLand in lstLand)
            {
                if (!string.IsNullOrEmpty(itemLand.Description))
                {
                    itemLand.Description = Regex.Replace(itemLand.Description, @"<img\s[^>]*>(?:\s*?/>)?", "", RegexOptions.IgnoreCase);
                    itemLand.Description = Regex.Replace(itemLand.Description, @"<(.|\n)*?>", string.Empty);
                    int descLength = itemLand.Description.Length;
                    if (descLength > 350)
                        itemLand.Description = itemLand.Description.Substring(0, 350) + "...";
                }
            }
            ViewBag.lstLand = lstLand;
            return PartialView("UC_Us_Land_List");

        }
        #endregion


    }
}
